<!-- Licensed under a BSD license. See license.html for license -->
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
    <title>WebGL - Scene Graph - Solar System</title>
    <link type="text/css" href="../resources/webgl-tutorials.css" rel="stylesheet" />
</head>

<body>
    <div id="info">
        <div class="description">
            Simulating a solar system using a scene graph.
        </div>
        <a href="https://webglfundamentals.org/webgl/lessons/zh_cn/webgl-scene-graph.html" target="_blank">WebGL -
            场景图</a>
    </div>
    <canvas id="canvas"></canvas>
</body>
<!-- vertex shader -->
<script id="3d-vertex-shader" type="x-shader/x-vertex">
attribute vec4 a_position;
attribute vec4 a_color;

uniform mat4 u_matrix;

varying vec4 v_color;

void main() {
    // Multiply the position by the matrix.
    gl_Position = u_matrix * a_position;

    // Pass the color to the fragment shader.
    v_color = a_color;
}
</script>
<!-- fragment shader -->
<script id="3d-fragment-shader" type="x-shader/x-fragment">
precision mediump float;

// Passed in from the vertex shader.
varying vec4 v_color;

uniform vec4 u_colorMult;
uniform vec4 u_colorOffset;

void main() {
    gl_FragColor = v_color * u_colorMult + u_colorOffset;
}
</script>
<!--
for most samples webgl-utils only provides shader compiling/linking and
canvas resizing because why clutter the examples with code that's the same in every sample.
See http://webglfundamentals.org/webgl/lessons/webgl-boilerplate.html
and http://webglfundamentals.org/webgl/lessons/webgl-resizing-the-canvas.html
for webgl-utils, m3, m4, and webgl-lessons-ui.
-->
<script src="../resources/webgl-utils.js"></script>
<script src="../resources/m4.js"></script>
<script src="../resources/primitives.js"></script>
<script>
    "use strict";

    var Node = function () {
        this.children = [];                 // 子节点序列
        this.localMatrix = m4.identity();   // 当前节点的局部矩阵
        this.worldMatrix = m4.identity();   // 当前结点的世界矩阵
    };

    Node.prototype.setParent = function (parent) {
        // 从父节点中移除
        if (this.parent) {
            var ndx = this.parent.children.indexOf(this);
            if (ndx >= 0) {
                this.parent.children.splice(ndx, 1);
            }
        }

        // 添加到新的父节点上
        if (parent) {
            parent.children.push(this);
        }
        this.parent = parent;
    };

    Node.prototype.updateWorldMatrix = function (parentWorldMatrix) {
        if (parentWorldMatrix) {
            // 传入一个矩阵计算出世界矩阵并存入 `this.worldMatrix`。
            m4.multiply(parentWorldMatrix, this.localMatrix, this.worldMatrix);
        } else {
            // 没有矩阵传入，直接将局部矩阵拷贝到世界矩阵
            m4.copy(this.localMatrix, this.worldMatrix);
        }

        // 计算所有的子节点
        var worldMatrix = this.worldMatrix;
        this.children.forEach(function (child) {
            child.updateWorldMatrix(worldMatrix);
        });
    };



    function main() {
        // Get A WebGL context
        /** @type {HTMLCanvasElement} */
        var canvas = document.getElementById("canvas");
        var gl = canvas.getContext("webgl");
        if (!gl) {
            return;
        }

        var createFlattenedVertices = function (gl, vertices) {
            var last;
            return webglUtils.createBufferInfoFromArrays(
                gl,
                primitives.makeRandomVertexColors(
                    primitives.deindexVertices(vertices),
                    {
                        vertsPerColor: 1,
                        rand: function (ndx, channel) {
                            if (channel === 0) {
                                last = 128 + Math.random() * 128 | 0;
                            }
                            return channel < 3 ? last : 255;
                        }
                    })
            );
        };

        var sphereBufferInfo = createFlattenedVertices(gl, primitives.createSphereVertices(10, 12, 6));

        // setup GLSL program
        var programInfo = webglUtils.createProgramInfo(gl, ["3d-vertex-shader", "3d-fragment-shader"]);

        function degToRad(d) {
            return d * Math.PI / 180;
        }

        function rand(min, max) {
            return Math.random() * (max - min) + min;
        }

        function emod(x, n) {
            return x >= 0 ? (x % n) : ((n - (-x % n)) % n);
        }


        var cameraAngleRadians = degToRad(0);
        var fieldOfViewRadians = degToRad(60);
        var cameraHeight = 50;

        var objectsToDraw = [];
        var objects = [];

        // 定义所有的节点
        var sunNode = new Node();
        sunNode.localMatrix = m4.translation(0, 0, 0);  // 太阳在中心
        sunNode.drawInfo = {
            uniforms: {
                u_colorOffset: [0.6, 0.6, 0, 1], // 黄色
                u_colorMult: [0.4, 0.4, 0, 1],
            },
            programInfo: programInfo,
            bufferInfo: sphereBufferInfo,
        };

        var earthNode = new Node();
        earthNode.localMatrix = m4.translation(100, 0, 0);  // 地球离太阳 100 个单位距离
        earthNode.drawInfo = {
            uniforms: {
                u_colorOffset: [0.2, 0.5, 0.8, 1],  // 蓝绿色
                u_colorMult: [0.8, 0.5, 0.2, 1],
            },
            programInfo: programInfo,
            bufferInfo: sphereBufferInfo,
        };

        var moonNode = new Node();
        moonNode.localMatrix = m4.translation(20, 0, 0);  // 月亮离地球 20 个单位距离
        moonNode.drawInfo = {
            uniforms: {
                u_colorOffset: [0.6, 0.6, 0.6, 1],  // 灰色
                u_colorMult: [0.1, 0.1, 0.1, 1],
            },
            programInfo: programInfo,
            bufferInfo: sphereBufferInfo,
        };


        // 关联物体
        moonNode.setParent(earthNode);
        earthNode.setParent(sunNode);

        var objects = [
            sunNode,
            earthNode,
            moonNode,
        ];

        var objectsToDraw = [
            sunNode.drawInfo,
            earthNode.drawInfo,
            moonNode.drawInfo,
        ];

        requestAnimationFrame(drawScene);

        // Draw the scene.
        function drawScene(time) {
            time *= 0.0005;

            webglUtils.resizeCanvasToDisplaySize(gl.canvas);

            // Tell WebGL how to convert from clip space to pixels
            gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);

            gl.enable(gl.CULL_FACE);
            gl.enable(gl.DEPTH_TEST);

            // Clear the canvas AND the depth buffer.
            gl.clearColor(0, 0, 0, 1);
            gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

            // Compute the projection matrix
            var aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
            var projectionMatrix =
                m4.perspective(fieldOfViewRadians, aspect, 1, 2000);

            // Compute the camera's matrix using look at.
            var cameraPosition = [0, -200, 0];
            var target = [0, 0, 0];
            var up = [0, 0, 1];
            var cameraMatrix = m4.lookAt(cameraPosition, target, up);

            // Make a view matrix from the camera matrix.
            var viewMatrix = m4.inverse(cameraMatrix);

            var viewProjectionMatrix = m4.multiply(projectionMatrix, viewMatrix);

            // 更新每个物体的局部矩阵
            m4.multiply(m4.yRotation(0.01), sunNode.localMatrix, sunNode.localMatrix);
            m4.multiply(m4.yRotation(0.01), earthNode.localMatrix, earthNode.localMatrix);
            m4.multiply(m4.yRotation(0.01), moonNode.localMatrix, moonNode.localMatrix);

            // Update all world matrices in the scene graph
            sunNode.updateWorldMatrix();

            // 计算每个物体的矩阵
            objects.forEach(function (object) {
                object.drawInfo.uniforms.u_matrix = m4.multiply(viewProjectionMatrix, object.worldMatrix);
            });

            // ------ Draw the objects --------

            var lastUsedProgramInfo = null;
            var lastUsedBufferInfo = null;

            objectsToDraw.forEach(function (object) {
                var programInfo = object.programInfo;
                var bufferInfo = object.bufferInfo;
                var bindBuffers = false;

                if (programInfo !== lastUsedProgramInfo) {
                    lastUsedProgramInfo = programInfo;
                    gl.useProgram(programInfo.program);

                    // We have to rebind buffers when changing programs because we
                    // only bind buffers the program uses. So if 2 programs use the same
                    // bufferInfo but the 1st one uses only positions the when the
                    // we switch to the 2nd one some of the attributes will not be on.
                    bindBuffers = true;
                }

                // Setup all the needed attributes.
                if (bindBuffers || bufferInfo !== lastUsedBufferInfo) {
                    lastUsedBufferInfo = bufferInfo;
                    webglUtils.setBuffersAndAttributes(gl, programInfo, bufferInfo);
                }

                // Set the uniforms.
                webglUtils.setUniforms(programInfo, object.uniforms);

                // Draw
                gl.drawArrays(gl.TRIANGLES, 0, bufferInfo.numElements);
            });

            requestAnimationFrame(drawScene);
        }
    }

    main();
</script>

</html>